<template>
	<view class="bond-pages">
		<SelectHouse :info="selectInfo" />
		<view class="info-block">
			<Card name="保证金缴纳">
				<view class="info-item">
					<view class="info-title">标准：</view>
					<view class="info-text">{{ info.area }}元/㎡（建筑面积）</view>
				</view>
				<view class="info-item">
					<view class="info-title">金额：</view>
					<view class="info-price">{{ info.price }}</view>
					<view class="unit">元</view>
					<view class="iconfont icon-a-jinggao1" @click="handleCalculatorClick" />
				</view>
			</Card>

			<radio-group @change="changeGroup" class="radio-item">
				<radio style="transform:scale(0.7)" color="#fb4744" :checked="form.checked" />
				<view class="text">我已阅读并同意</view>
				<view class="text red" @click="navigate('/page_pack/bond/mp-html')">
					《保证金缴纳用户须知》
				</view>
			</radio-group>

			<view class="btn normal" @click="handleSubmit">
				<view class="price">￥{{ info.price }}</view>确认缴纳
			</view>
		</view>
	</view>
</template>

<script>
	import {
		SelectHouse
	} from '@/components/SelectHouse.vue'
	import {
		Card
	} from '@/components/Card/Card.vue'
	import {
		getStorage
	} from '@/util/auth.js'
	import {
		validate
	} from '@/util/validate.js'
	import {
		payment
	} from '@/api/payment.js'
	import {
		debounce
	} from 'lodash';

	const PAYMENT_TYPE = 1

	export default {
		components: {
			SelectHouse,
			Card
		},
		data() {
			return {
				selectId: 1,
				info: {
					id: '',
					area: '',
					price: '',
					houseType: '',
					idValue: '',
					payableDeposit: '',
					publicRental: 0,
					lowRent: 0,
					straightPipe: 0
				},
				form: {
					checked: false,
				},
				rule: {
					checked: {
						name: '',
						required: false,
						validator: this.validateAgreement
					},
				},
				selectInfo: {},
				paymentStatusTimer: null // 支付状态轮询定时器
			}
		},
		methods: {
			handleCalculatorClick() {
				const {
					price,
					publicRental,
					lowRent,
					straightPipe
				} = this.info
				this.navigate(
					`/page_pack/bond/calculator?type=4&price=${price}&lowRent=${lowRent}&publicRental=${publicRental}&straightPipe=${straightPipe}`
				)
			},

			changeGroup() {
				this.form.checked = !this.form.checked
			},

			validateAgreement(value, form, callback) {
				if (value === false) {
					callback('请阅读并同意《保证金缴纳用户须知》！')
				}
				callback()
			},

			handleSubmit: debounce(function() {
				this._handleSubmit();
			}, 1000, {
				leading: true,
				trailing: false
			}),

			async _handleSubmit() {
				if (!validate(this.form, this.rule)) {
					return
				}

				uni.showLoading({
					title: '准备支付...',
					mask: true
				})

				try {
					const paymentData = {
						payableDeposit: this.info.payableDeposit,
						idValue: this.info.idValue,
						type: PAYMENT_TYPE,
						depositPaid: this.info.price
					}

					const res = await payment(paymentData)

					if (!res || !res.payUrl) {
						this.showToast('支付通道初始化失败')
						return
					}

					// 启动支付状态轮询（防止小程序未回调的情况）
					this.startPaymentStatusCheck(res.orderId)

					wx.openEmbeddedMiniProgram({
						appId: 'wxe457b27e56342156',
						path: res.payUrl,
						extraData: {
							orderId: res.orderId,
							amount: this.info.price
						},
						 envVersion: 'release', // develop-开发版 trial-体验版 release-正式版
						success: (res) => {
							console.log('小程序跳转成功', res)
						},
						fail: (err) => {
							this.clearPaymentTimer()
							console.error('完整错误:', err.errMsg, err)
							let msg = '支付通道打开失败'
							if (err.errMsg.includes('cancel')) {
								msg = '您已取消支付'
							}
							this.showToast(msg)
						}
					})

				} catch (error) {
					console.error('支付异常:', error)
					this.showToast('支付异常，请重试')
				} finally {
					uni.hideLoading()
				}
			},

			// 支付状态轮询
			startPaymentStatusCheck(orderId) {
				this.clearPaymentTimer()
				let checkCount = 0
				const maxCheckCount = 6 // 30秒（5秒一次）

				this.paymentStatusTimer = setInterval(async () => {
					checkCount++
					try {
						const res = await this.checkPaymentStatus(orderId)
						if (res.paid) {
							this.clearPaymentTimer()
							this.showSuccessToast(this.info.price, this.info.area, this.info.id)
						} else if (checkCount >= maxCheckCount) {
							this.clearPaymentTimer()
							this.showToast('支付状态确认超时，请到订单中心查看')
						}
					} catch (error) {
						console.error('支付状态查询异常:', error)
						if (checkCount >= maxCheckCount) {
							this.clearPaymentTimer()
						}
					}
				}, 5000)
			},

			clearPaymentTimer() {
				if (this.paymentStatusTimer) {
					clearInterval(this.paymentStatusTimer)
					this.paymentStatusTimer = null
				}
			},

			// 模拟支付状态检查API
			async checkPaymentStatus(orderId) {
				return new Promise(resolve => {
					setTimeout(() => {
						// 实际项目中这里应该是API请求
						resolve({
							paid: false
						}) // 模拟返回
					}, 300)
				})
			},

			showSuccessToast(price, area, id) {
				uni.showToast({
					title: '缴纳成功',
					duration: 2000,
					mask: true,
				})

				uni.redirectTo({
					url: `/page_pack/pay_success/pay_success?price=${price}&area=${area}&id=${id}`
				})
			},

			showToast(message) {
				uni.showToast({
					title: message,
					icon: 'none',
					duration: 2000
				})
			},

			navigate(url) {
				uni.navigateTo({
					url
				})
			},

			initPageData(e) {
				this.selectId = getStorage('selectId');
				this.selectInfo = getStorage('selectInfo')
				this.info = {
					id: e.id,
					area: e.buildingArea,
					price: e.price,
					houseType: e.houseType,
					idValue: e.idValue,
					payableDeposit: e.payableTotalPrice
				};

				if (this.selectInfo.fwSecurityDepositConfigList?.length > 0) {
					this.selectInfo.fwSecurityDepositConfigList.forEach(item => {
						switch (item.houseType) {
							case '廉租房':
								this.info.lowRent = item.chargingStandard;
								break;
							case '公租房':
								this.info.publicRental = item.chargingStandard;
								break;
							case '直管公房':
								this.info.straightPipe = item.chargingStandard;
								break;
						}
					});
				}
			}
		},
		onLoad(e) {
			this.initPageData(e)
		},
		onShow() {
			this.selectInfo = getStorage('selectInfo')
		},
		onUnload() {
			this.clearPaymentTimer()
		}
	}
</script>

<style lang="scss">
	.bond-pages {
		padding: 30rpx;

		.info-block {
			margin-top: 30rpx;

			.info-item {
				display: flex;
				align-items: center;
				font-size: 32rpx;
				line-height: 80rpx;

				.info-price {
					color: $theme-color;
					font-weight: bold;
				}

				.iconfont {
					margin-left: 20rpx;
					font-size: 30rpx;
					color: #767676;
				}
			}

			.radio-item {
				display: flex;
				align-items: center;
				margin: 40rpx 0;

				.text {
					font-size: 28rpx;
					color: #767676;
				}

				.red {
					color: $theme-color;
					font-weight: bold;
				}
			}

			.btn {
				border-radius: 20rpx;
				height: 100rpx;
				font-size: 32rpx;

				.price {
					margin-right: 10rpx;
				}
			}
		}
	}
</style>